
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块

//商品详情
function goodsDetailModel() {
    return async (req, res) => {
        // let [err, data] = await to(db.query(`SELECT * FROM category_first`, [HOST]));
        // err ? ERROR(res, '商品详情查询失败', err) : SUCCESS(res, data);
        let { goodsid } = req.query;
        //访问数据库，获取四个promise对象
        let p1 = getGoodsList(goodsid);
        let p2 = getEvalList(goodsid);
        let p3 = getImgList(goodsid);
        let p4 = getStyleList(goodsid);
        let [err, data] = await to(Promise.all([p1, p2, p3, p4]));
        if (err) {
            ERROR(res, '商品详情出错', err);
            return;
        }
        //成功获取到数据
        // console.log(data);
        let obj=data[0][0];//将商品详情保存在对象中
        obj.evalList=data[1];//评论列表
        obj.imageList=data[2];//图片列表
        obj.styleList=data[3];//规格列表
        SUCCESS(res,obj);
    };
}

//获取商品信息
function getGoodsList(id) {
    return db.query(`SELECT a.id,a.goods_id,a.first_id,a.second_id,a.thired_id,a.goods_name,CONCAT(?,a.image_url) as image_url,a.goods_introduce,a.goods_manufacturer,
    a.goods_price,a.assem_price,a.goods_detailed_information,a.new_status,b.first_name,c.second_name,d.thired_name FROM goods_list as a
   INNER JOIN category_first as b
   ON a.first_id=b.first_id
   INNER JOIN category_second as c
   ON a.second_id=c.second_id
   INNER JOIN category_thired as d
   ON a.thired_id=d.thired_id
   WHERE a.goods_id=?`, [HOST, id]);//返回值为promise
}

//获取图片列表
function getImgList(id) {
    return db.query(`SELECT b.uid,b.username,CONCAT(?,b.head_photo_url) as head_photo_url ,a.eval_text,a.eval_start,a.create_time FROM goods_eval as a
    INNER JOIN member as b
    ON a.uid=b.uid
    WHERE a.goods_id=?`,[HOST,id]);
}

//获取评论信息
function getEvalList(id) {
    return db.query(`SELECT CONCAT(?,file_name) as file_name FROM goods_image WHERE goods_id=?`,[HOST,id]);
}

//商品规格信息
function getStyleList(id) {
    return db.query(`SELECT * FROM goods_style WHERE goods_id=?`,[id]);
}


module.exports = goodsDetailModel;